import tkinter as tk
from tkinter import ttk, messagebox
import customtkinter
from ui.pages.scrollable_page import ScrollablePage
from core.utils.image_utils import load_thumbnail
from core.utils.logger import debug, info, warning, error
from core.utils.error_handler import ErrorHandler
from core.utils.ui_optimizer import load_products_async, load_image_async, show_loading, hide_loading
from core.utils.i18n import t
from core.services.data_manager import DataManager
from ui.styles.theme import Theme

class ProductPage(ScrollablePage):
    def __init__(self, parent, controller):
        # 初始化搜索历史属性
        self.search_history = []
        # 初始化数据管理器
        self.dm = DataManager()
        # 调用父类初始化
        super().__init__(parent, controller)
    
    def create_widgets(self):
        debug("ProductPage: Creating widgets...")
        
        # 加载搜索历史
        self.load_search_history()
        
        # 使用滚动框架
        content_frame = self.scrollable_frame
        
        # 创建顶部导航栏
        self.create_navbar(content_frame)
        
        # 创建轮播图
        self.create_carousel(content_frame)
        
        # 创建工具栏（包含筛选按钮）
        self.create_toolbar(content_frame)
        
        # 创建内容区域
        self.create_content_area(content_frame)
        
        # 初始加载商品
        self.load_products()
        
        # 初始化筛选变量
        self.initialize_filter_vars()
        
        # 加载显示设置
        self.load_display_settings()
    
    def load_display_settings(self):
        """加载显示设置"""
        try:
            settings = self.dm.load_data('settings.json') or {}
            self.products_per_page = int(settings.get('products_per_page', '9'))
            self.card_size = settings.get('card_size', 'medium')
            
            # 根据卡片尺寸设置不同的尺寸参数
            self.card_sizes = {
                'small': {'width': 200, 'height': 250, 'image_width': 150, 'image_height': 120},
                'medium': {'width': 250, 'height': 300, 'image_width': 180, 'image_height': 150},
                'large': {'width': 300, 'height': 350, 'image_width': 220, 'image_height': 180}
            }
            
            debug(f"Display settings loaded: products_per_page={self.products_per_page}, card_size={self.card_size}")
        except Exception as e:
            error(f"Failed to load display settings: {e}")
            # 使用默认值
            self.products_per_page = 9
            self.card_size = 'medium'
            self.card_sizes = {
                'small': {'width': 200, 'height': 250, 'image_width': 150, 'image_height': 120},
                'medium': {'width': 250, 'height': 300, 'image_width': 180, 'image_height': 150},
                'large': {'width': 300, 'height': 350, 'image_width': 220, 'image_height': 180}
            }
    
    def refresh_display_settings(self):
        """刷新显示设置并重新加载商品"""
        try:
            self.load_display_settings()
            # 重新加载商品以应用新设置
            self.load_products()
            debug("Display settings refreshed")
        except Exception as e:
            error(f"Failed to refresh display settings: {e}")
    
    def refresh_language(self):
        """刷新语言显示"""
        try:
            # 刷新导航栏
            if hasattr(self, 'logo_label'):
                self.logo_label.configure(text=t("product.logo"))
            if hasattr(self, 'search_btn'):
                self.search_btn.configure(text=t("product.search"))
            if hasattr(self, 'cart_btn'):
                self.cart_btn.configure(text=t("product.cart"))
            if hasattr(self, 'orders_btn'):
                self.orders_btn.configure(text=t("product.orders"))
            if hasattr(self, 'account_btn'):
                self.account_btn.configure(text=t("product.account"))
            
            # 刷新筛选按钮
            if hasattr(self, 'filter_buttons'):
                for category, btn in self.filter_buttons.items():
                    btn.config(text=t(f"product.categories.{category}"))
            
            # 重新加载产品列表以更新产品名称显示
            self.load_products()
            
            debug("ProductPage language refreshed")
        except Exception as e:
            error(f"Failed to refresh language in ProductPage: {e}")
    
    def create_carousel(self, parent):
        """创建轮播图"""
        from ui.components.carousel import Carousel
        
        # 获取热门商品作为轮播图内容
        def get_carousel_items():
            products = self.controller.product_service.get_all_products()
            # 选择前5个商品作为轮播图内容
            carousel_products = products[:5]
            items = []
            
            for product in carousel_products:
                product_name = product.get_display_name() if hasattr(product, 'get_display_name') else (getattr(product, 'name_en', None) or product.name)
                items.append({
                    'image_path': getattr(product, 'image_path', None),
                    'title': product_name,
                    'subtitle': f"¥{product.price:.2f} - {product.description[:50]}...",
                    'action': lambda p=product: self.view_product_detail(p)
                })
            
            # 如果没有商品，使用默认内容
            if not items:
                items = [{
                    'image_path': None,
                    'title': t("carousel.welcome"),
                    'subtitle': t("carousel.subtitle"),
                    'action': None
                }]
            
            return items
        
        carousel_items = get_carousel_items()
        
        # 创建轮播图
        self.carousel = Carousel(
            parent,
            items=carousel_items,
            auto_play=True,
            interval=4000
        )
        self.carousel.pack(fill='x', padx=20, pady=(10, 0))
    
    def initialize_filter_vars(self):
        """初始化筛选变量"""
        self.category_var = tk.StringVar(value="all")
        self.price_var = tk.StringVar(value="all")
        self.min_price_var = tk.StringVar()
        self.max_price_var = tk.StringVar()
        self.stock_var = tk.StringVar(value="all")
        self.sort_var = tk.StringVar(value="name_asc")
        self.current_filters = {}
    
    def create_navbar(self, parent):
        """创建顶部导航栏 - 淘宝风格"""
        # 导航栏主容器
        navbar = customtkinter.CTkFrame(parent, fg_color="transparent")
        navbar.pack(fill="x", padx=15, pady=10)
        
        # 第一行：主要功能区
        top_row = customtkinter.CTkFrame(navbar, fg_color="transparent")
        top_row.pack(fill="x")
        
        # Logo区域
        logo_frame = customtkinter.CTkFrame(top_row, fg_color="transparent")
        logo_frame.pack(side="left")
        
        accent_color = Theme.get_color('accent')
        logo_label = customtkinter.CTkLabel(
            logo_frame, 
            text="🛍️ Ali Bao Bao", 
            font=("Arial", 20, "bold"),
            text_color=accent_color
        )
        logo_label.pack(side="left")
        
        # 搜索区域
        search_frame = customtkinter.CTkFrame(top_row, fg_color="transparent")
        search_frame.pack(side="left", padx=30, fill="x", expand=True)
        
        # 搜索框
        self.search_entry = customtkinter.CTkEntry(
            search_frame,
            placeholder_text="Search products...",
            width=300,  # 限制搜索框宽度
            height=40,
            font=('Arial', 12)
        )
        self.search_entry.pack(side="left", padx=(0, 10))
        self.search_entry.bind('<Return>', lambda e: self.search_products())
        self.search_entry.bind('<KeyRelease>', lambda e: self._debounced_search())
        
        search_btn = customtkinter.CTkButton(
            search_frame, 
            text="🔍 Search", 
            command=self.search_products,
            width=100,
            height=40,
            font=('Arial', 12, 'bold'),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover')
        )
        search_btn.pack(side="left")
        
        # 用户功能区
        user_area = customtkinter.CTkFrame(top_row, fg_color="transparent")
        user_area.pack(side="right")
        
        # 购物车按钮带数量
        self.cart_frame = customtkinter.CTkFrame(user_area, fg_color="transparent")
        self.cart_frame.pack(side="left", padx=5)
        
        self.cart_btn = customtkinter.CTkButton(
            self.cart_frame,
            text="🛒 Cart",
            command=self.show_cart,
            width=90,
            height=32,
            font=('Arial', 11)
        )
        self.cart_btn.pack(side="left")
        
        self.cart_count_label = ttk.Label(
            self.cart_frame,
            text="0",
            font=("Arial", 8, "bold"),
            foreground="white",
            background="#FF6B35",
            padding=(4, 1)
        )
        
        # 订单按钮
        self.orders_btn = customtkinter.CTkButton(
            user_area,
            text="📦 Orders",
            command=self.show_orders,
            width=90,
            height=32,
            font=('Arial', 11)
        )
        self.orders_btn.pack(side="left", padx=5)
        
        # 用户账户按钮
        self.profile_btn = customtkinter.CTkButton(
            user_area,
            text="👤 Account",
            command=self.show_profile,
            width=90,
            height=32,
            font=('Arial', 11)
        )
        self.profile_btn.pack(side="left", padx=5)
        
        # 角色切换器
        from ui.components.role_switcher import RoleSwitcher
        self.role_switcher = RoleSwitcher(user_area, self.controller)
        self.role_switcher.pack(side="left", padx=5)
        
    
    def create_search_shortcuts(self, parent):
        """创建搜索快捷栏 - 只显示历史搜索"""
        shortcuts_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        shortcuts_frame.pack(fill="x", pady=(5, 0))
        
        # 历史搜索标签
        history_label = customtkinter.CTkLabel(
            shortcuts_frame,
            text=t("product.search.history_search"),
            font=("Arial", 9, "bold"),
            text_color=Theme.get_color('fg_tertiary')
        )
        history_label.pack(side="left", padx=(0, 10))
        
        # 历史搜索容器
        self.history_container = customtkinter.CTkFrame(shortcuts_frame, fg_color="transparent")
        self.history_container.pack(side="left", fill="x", expand=True)
        
        # 更新历史搜索显示
        self.update_search_history_display()
    
    def create_quick_categories(self, parent):
        """创建快速分类导航"""
        category_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        category_frame.pack(fill="x", pady=(10, 0))
        
        categories = [
            ("🔥 Hot", "hot"),
            ("📱 Electronics", "electronics"),
            ("👗 Clothing", "clothing"), 
            ("📚 Books", "books"),
            ("🏠 Home", "home"),
            ("💄 Beauty", "beauty"),
            ("🛒 Deals", "deals")
        ]
        
        for text, category_id in categories:
            btn = customtkinter.CTkButton(
                category_frame,
                text=text,
                command=lambda cid=category_id: self.quick_filter(cid),
                width=120,
                height=32,
                font=('Arial', 11),
                fg_color=("gray90", "gray25"),
                hover_color=Theme.get_color('accent_hover')
            )
            btn.pack(side="left", padx=5)
    
    def create_toolbar(self, parent):
        """创建工具栏"""
        toolbar = customtkinter.CTkFrame(parent, fg_color=("gray95", "gray20"), corner_radius=10)
        toolbar.pack(fill="x", padx=20, pady=15)
        
        # 左侧：筛选和排序
        left_toolbar = customtkinter.CTkFrame(toolbar, fg_color="transparent")
        left_toolbar.pack(side="left", padx=15, pady=12)
        
        # 筛选按钮
        filter_btn = customtkinter.CTkButton(
            left_toolbar,
            text="🔍 Filter & Sort",
            command=self.show_filter_dialog,
            width=150,
            height=38,
            font=('Arial', 13, "bold"),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        )
        filter_btn.pack(side="left", padx=(0, 12))
        
        # 当前筛选状态显示
        self.filter_status_label = customtkinter.CTkLabel(
            left_toolbar,
            text="Showing all products",
            font=("Arial", 11),
            text_color=Theme.get_color('fg_secondary')
        )
        self.filter_status_label.pack(side="left", padx=10)
        
        # 清除筛选按钮
        self.clear_filter_btn = customtkinter.CTkButton(
            left_toolbar,
            text="Clear Filters",
            command=self.clear_filters,
            state="disabled",
            width=110,
            height=38,
            font=('Arial', 12),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=8
        )
        self.clear_filter_btn.pack(side="left", padx=5)
        
        # 右侧：商品计数
        right_toolbar = customtkinter.CTkFrame(toolbar, fg_color="transparent")
        right_toolbar.pack(side="right", padx=15, pady=12)
        
        self.product_count_label = customtkinter.CTkLabel(
            right_toolbar,
            text="Loading...",
            font=("Arial", 12, 'bold'),
            text_color=Theme.get_color('fg_primary')
        )
        self.product_count_label.pack()
    
    def create_content_area(self, parent):
        """创建内容区域"""
        # 商品展示区域
        products_container = customtkinter.CTkFrame(parent, fg_color="transparent")
        products_container.pack(fill="both", expand=True, padx=20, pady=10)
        
        # 商品网格容器
        self.products_grid = customtkinter.CTkFrame(products_container, fg_color="transparent")
        self.products_grid.pack(fill="both", expand=True)
    
    
    def quick_filter(self, category_id):
        """快速分类筛选"""
        quick_filters = {
            "hot": {"sort_by": "name_asc"},  # 暂时使用名称排序，后续可添加热门度字段
            "electronics": {"category": "electronics"},
            "clothing": {"category": "clothing"},
            "books": {"category": "books"},
            "home": {"category": "home"},
            "beauty": {"category": "beauty"},
            "deals": {"price_range": "0-50"}
        }
        
        if category_id in quick_filters:
            filters = quick_filters[category_id]
            self.apply_quick_filters(filters)
    
    def apply_quick_filters(self, filters):
        """应用快速筛选"""
        # 更新筛选变量
        if "category" in filters:
            self.category_var.set(filters["category"])
        if "price_range" in filters:
            self.price_var.set(filters["price_range"])
        if "sort_by" in filters:
            self.sort_var.set(filters["sort_by"])
        
        # 构建完整的筛选条件
        full_filters = {
            'category': self.category_var.get(),
            'price_range': self.price_var.get(),
            'min_price': self.min_price_var.get(),
            'max_price': self.max_price_var.get(),
            'stock_status': self.stock_var.get(),
            'sort_by': self.sort_var.get()
        }
        
        # 保存当前筛选
        self.current_filters = full_filters
        
        # 应用筛选
        self.apply_filter_logic(full_filters)
        
        # 更新筛选状态显示
        self.update_filter_status(full_filters)
        
        # 启用清除筛选按钮
        self.clear_filter_btn.configure(state="normal")
    
    def show_filter_dialog(self):
        """显示筛选对话框"""
        # 创建顶级窗口
        filter_window = customtkinter.CTkToplevel(self)
        filter_window.title("Advanced Filter & Sort")
        filter_window.geometry("550x700")
        filter_window.resizable(True, True)
        
        # 使对话框模态化
        filter_window.transient(self)
        filter_window.grab_set()
        
        # 居中显示
        filter_window.update_idletasks()
        x = (self.winfo_screenwidth() // 2) - (550 // 2)
        y = (self.winfo_screenheight() // 2) - (700 // 2)
        filter_window.geometry(f"+{x}+{y}")
        
        # 创建可滚动的筛选内容区域并固定底部按钮
        # 主容器（包含滚动区域和底部按钮区）
        container = customtkinter.CTkFrame(filter_window, fg_color="transparent")
        container.pack(fill='both', expand=True)

        # Canvas + scrollbar 用于滚动内容
        canvas = tk.Canvas(container, borderwidth=0, highlightthickness=0, bg=Theme.get_color('bg_primary'))
        vsb = ttk.Scrollbar(container, orient='vertical', command=canvas.yview)
        canvas.configure(yscrollcommand=vsb.set)

        vsb.pack(side='right', fill='y')
        canvas.pack(side='left', fill='both', expand=True)

        # 内部 frame 放置实际内容
        inner = customtkinter.CTkFrame(canvas, fg_color="transparent")
        # 将 inner 放入 canvas
        canvas.create_window((0, 0), window=inner, anchor='nw')

        # 绑定尺寸变化以调整 scrollregion
        def _on_frame_configure(event):
            canvas.configure(scrollregion=canvas.bbox('all'))

        inner.bind('<Configure>', _on_frame_configure)

        # 鼠标滚轮支持（Windows / Mac）
        def _on_mousewheel(event):
            # Windows: event.delta (multiples of 120), Mac: event.delta small
            delta = int(-1 * (event.delta / 120)) if event.delta else 0
            canvas.yview_scroll(delta, 'units')

        # bind to both canvas and inner so wheel works when hovering
        canvas.bind_all('<MouseWheel>', _on_mousewheel)

        # 创建筛选内容到 inner
        self.create_filter_content(inner)

        # 底部按钮区（固定在 dialog 底部）
        btn_bottom = customtkinter.CTkFrame(filter_window, fg_color="transparent")
        btn_bottom.pack(side='bottom', fill='x', padx=20, pady=15)
        # 将原有按钮创建函数改为接受父容器，这里把按钮放到底部
        self.create_filter_buttons(filter_window, btn_bottom)
    
    def create_filter_content(self, parent):
        """创建筛选对话框内容"""
        # 主容器
        main_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        main_frame.pack(fill="both", expand=True, padx=20, pady=20)

        # 标题
        title_label = customtkinter.CTkLabel(
            main_frame,
            text="🔍 Advanced Filter",
            font=("Arial", 20, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(pady=(10, 30))

        # 创建各个筛选部分
        self.create_category_filter(main_frame)
        self.create_price_filter(main_frame)
        self.create_stock_filter(main_frame)
        self.create_sort_options(main_frame)
    
    def create_category_filter(self, parent):
        """创建商品类型筛选"""
        category_frame = customtkinter.CTkFrame(parent)
        category_frame.pack(fill="x", pady=12)
        
        # 标题
        category_title = customtkinter.CTkLabel(
            category_frame,
            text="📁 Category",
            font=("Arial", 14, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        category_title.pack(anchor="w", padx=15, pady=15)
        
        categories = [
            ("All Categories", "all"),
            ("📱 Electronics", "electronics"),
            ("👗 Clothing", "clothing"),
            ("📚 Books", "books"),
            ("🏠 Home & Living", "home"),
            ("💄 Beauty & Skincare", "beauty")
        ]
        
        for text, value in categories:
            radio = customtkinter.CTkRadioButton(
                category_frame,
                text=text,
                variable=self.category_var,
                value=value,
                font=("Arial", 12)
            )
            radio.pack(anchor="w", padx=15, pady=6)
    
    def create_price_filter(self, parent):
        """创建价格范围筛选"""
        price_frame = customtkinter.CTkFrame(parent)
        price_frame.pack(fill="x", pady=12)
        
        # 标题
        price_title = customtkinter.CTkLabel(
            price_frame,
            text="💰 Price Range",
            font=("Arial", 14, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        price_title.pack(anchor="w", padx=15, pady=15)
        
        price_ranges = [
            ("All Prices", "all"),
            ("Under ¥50", "0-50"),
            ("¥50 - ¥200", "50-200"),
            ("¥200 - ¥500", "200-500"),
            ("¥500 - ¥1000", "500-1000"),
            ("Above ¥1000", "1000+")
        ]
        
        for text, value in price_ranges:
            radio = customtkinter.CTkRadioButton(
                price_frame,
                text=text,
                variable=self.price_var,
                value=value,
                font=("Arial", 12)
            )
            radio.pack(anchor="w", padx=15, pady=6)
        
        # 自定义价格范围
        custom_frame = customtkinter.CTkFrame(price_frame, fg_color="transparent")
        custom_frame.pack(fill="x", pady=(10, 5), padx=15)
        
        customtkinter.CTkLabel(
            custom_frame, 
            text="Custom Range:", 
            font=("Arial", 11, "bold"),
            text_color=Theme.get_color('fg_primary')
        ).pack(anchor="w", pady=5)
        
        price_input_frame = customtkinter.CTkFrame(custom_frame, fg_color="transparent")
        price_input_frame.pack(fill="x", pady=5)
        
        customtkinter.CTkLabel(price_input_frame, text="¥", font=("Arial", 11)).pack(side="left")
        self.min_price_entry = customtkinter.CTkEntry(
            price_input_frame, 
            textvariable=self.min_price_var, 
            width=80, 
            height=30,
            font=("Arial", 11)
        )
        self.min_price_entry.pack(side="left", padx=5)
        customtkinter.CTkLabel(price_input_frame, text="to", font=("Arial", 11)).pack(side="left", padx=5)
        customtkinter.CTkLabel(price_input_frame, text="¥", font=("Arial", 11)).pack(side="left")
        self.max_price_entry = customtkinter.CTkEntry(
            price_input_frame, 
            textvariable=self.max_price_var, 
            width=80, 
            height=30,
            font=("Arial", 11)
        )
        self.max_price_entry.pack(side="left", padx=5)
        
        # 价格输入提示
        customtkinter.CTkLabel(
            custom_frame,
            text="💡 Enter numbers only, e.g., 50 to 200",
            font=("Arial", 9),
            text_color=Theme.get_color('fg_tertiary')
        ).pack(anchor="w", pady=(0, 10))
    
    def create_stock_filter(self, parent):
        """创建库存状态筛选"""
        stock_frame = customtkinter.CTkFrame(parent)
        stock_frame.pack(fill="x", pady=12)
        
        # 标题
        stock_title = customtkinter.CTkLabel(
            stock_frame,
            text="📦 Stock Status",
            font=("Arial", 14, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        stock_title.pack(anchor="w", padx=15, pady=15)
        
        stock_options = [
            ("All Products", "all"),
            ("✅ In Stock", "in_stock"),
            ("⚠️ Low Stock (1-10)", "low_stock"),
            ("❌ Out of Stock", "out_of_stock")
        ]
        
        for text, value in stock_options:
            radio = customtkinter.CTkRadioButton(
                stock_frame,
                text=text,
                variable=self.stock_var,
                value=value,
                font=("Arial", 12)
            )
            radio.pack(anchor="w", padx=15, pady=6)
    
    def create_sort_options(self, parent):
        """创建排序选项"""
        sort_frame = customtkinter.CTkFrame(parent)
        sort_frame.pack(fill="x", pady=12)
        
        # 标题
        sort_title = customtkinter.CTkLabel(
            sort_frame,
            text="📊 Sort By",
            font=("Arial", 14, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        sort_title.pack(anchor="w", padx=15, pady=15)
        
        sort_options = [
            ("Name: A to Z", "name_asc"),
            ("Name: Z to A", "name_desc"),
            ("Price: Low to High", "price_asc"),
            ("Price: High to Low", "price_desc"),
            ("🆕 Newest", "newest")
        ]
        
        for text, value in sort_options:
            radio = customtkinter.CTkRadioButton(
                sort_frame,
                text=text,
                variable=self.sort_var,
                value=value,
                font=("Arial", 12)
            )
            radio.pack(anchor="w", padx=15, pady=6)
    
    def create_filter_buttons(self, window, parent):
        """创建筛选对话框按钮"""
        button_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        button_frame.pack(fill="x")
        
        # 应用筛选按钮
        apply_btn = customtkinter.CTkButton(
            button_frame,
            text="✅ Apply",
            command=lambda: self.confirm_and_apply_filters(window),
            width=140,
            height=40,
            font=("Arial", 13, "bold"),
            fg_color=Theme.get_color('accent'),
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        )
        apply_btn.pack(side="left", padx=8)
        
        # 重置按钮
        reset_btn = customtkinter.CTkButton(
            button_frame,
            text="🔄 Reset",
            command=self.reset_filter_fields,
            width=120,
            height=40,
            font=("Arial", 13, "bold"),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=8
        )
        reset_btn.pack(side="left", padx=8)
        
        # 取消按钮
        cancel_btn = customtkinter.CTkButton(
            button_frame,
            text="❌ Cancel",
            command=window.destroy,
            width=120,
            height=40,
            font=("Arial", 13, "bold"),
            fg_color=("gray70", "gray30"),
            hover_color=("gray60", "gray40"),
            corner_radius=8
        )
        cancel_btn.pack(side="left", padx=8)
    
    def apply_filters(self, window):
        """应用筛选条件"""
        # 收集筛选条件
        filters = {
            'category': self.category_var.get(),
            'price_range': self.price_var.get(),
            'min_price': self.min_price_var.get(),
            'max_price': self.max_price_var.get(),
            'stock_status': self.stock_var.get(),
            'sort_by': self.sort_var.get()
        }
        
        debug(f"Applying filters: {filters}")
        
        # 更新筛选状态显示
        self.update_filter_status(filters)
        
        # 启用清除筛选按钮
        self.clear_filter_btn.configure(state="normal")
        
        # 应用筛选逻辑
        self.apply_filter_logic(filters)
        
        # 保存当前筛选
        self.current_filters = filters
        
        # 关闭对话框
        window.destroy()

    def confirm_and_apply_filters(self, window):
        """直接应用筛选，不再显示确认对话框"""
        self.apply_filters(window)
    
    def update_filter_status(self, filters):
        """更新筛选状态显示"""
        active_filters = []
        
        if filters['category'] != 'all':
            category_names = {
                'electronics': 'Electronics',
                'clothing': 'Clothing', 
                'books': 'Books',
                'home': 'Home',
                'beauty': 'Beauty',
                'toys': 'Toys',
                'sports': 'Sports'
            }
            active_filters.append(category_names.get(filters['category'], filters['category']))
        
        if filters['price_range'] != 'all':
            active_filters.append(f"Price: {filters['price_range']}")
        
        if filters['stock_status'] != 'all':
            stock_names = {
                'in_stock': 'In Stock',
                'low_stock': 'Low Stock',
                'out_of_stock': 'Out of Stock'
            }
            active_filters.append(stock_names.get(filters['stock_status'], filters['stock_status']))
        
        if active_filters:
            status_text = " | ".join(active_filters)
            self.filter_status_label.configure(text=status_text, text_color=Theme.get_color('accent'), font=("Arial", 11, "bold"))
        else:
            self.filter_status_label.configure(text="Showing all products", text_color=Theme.get_color('fg_secondary'), font=("Arial", 11))
    
    def apply_filter_logic(self, filters):
        """应用筛选逻辑到商品列表"""
        products = self.controller.product_service.get_all_products()
        original_count = len(products)
        
        # 应用分类筛选
        if filters['category'] != 'all':
            products = [p for p in products if p.get_category() == filters['category']]
        
        # 应用价格筛选
        if filters['price_range'] != 'all':
            if filters['price_range'] == '0-50':
                products = [p for p in products if p.price <= 50]
            elif filters['price_range'] == '50-200':
                products = [p for p in products if 50 <= p.price <= 200]
            elif filters['price_range'] == '200-500':
                products = [p for p in products if 200 <= p.price <= 500]
            elif filters['price_range'] == '500-1000':
                products = [p for p in products if 500 <= p.price <= 1000]
            elif filters['price_range'] == '1000+':
                products = [p for p in products if p.price > 1000]
        
        # 应用自定义价格范围
        if filters['min_price'] or filters['max_price']:
            try:
                min_price = float(filters['min_price']) if filters['min_price'] else 0
                max_price = float(filters['max_price']) if filters['max_price'] else float('inf')
                products = [p for p in products if min_price <= p.price <= max_price]
            except ValueError:
                messagebox.showerror(t("product.invalid_price"), t("product.enter_valid_price"))
                return
        
        # 应用库存筛选
        if filters['stock_status'] != 'all':
            if filters['stock_status'] == 'in_stock':
                products = [p for p in products if p.stock > 0]
            elif filters['stock_status'] == 'low_stock':
                products = [p for p in products if 0 < p.stock < 10]
            elif filters['stock_status'] == 'out_of_stock':
                products = [p for p in products if p.stock == 0]
        
        # 应用排序
        if filters['sort_by'] == 'name_asc':
            products.sort(key=lambda x: x.name.lower())
        elif filters['sort_by'] == 'name_desc':
            products.sort(key=lambda x: x.name.lower(), reverse=True)
        elif filters['sort_by'] == 'price_asc':
            products.sort(key=lambda x: x.price)
        elif filters['sort_by'] == 'price_desc':
            products.sort(key=lambda x: x.price, reverse=True)
        elif filters['sort_by'] == 'newest':
            products.reverse()
        # rating 和 popular 需要额外数据，这里暂时用名称排序
        elif filters['sort_by'] in ['rating', 'popular']:
            products.sort(key=lambda x: x.name.lower())
        
        # 更新商品计数
        filtered_count = len(products)
        self.product_count_label.configure(
            text=f"Showing {filtered_count}/{original_count} products"
        )
        
        # 重新加载筛选后的商品
        self.display_filtered_products(products)
    
    def display_filtered_products(self, products):
        """显示筛选后的商品"""
        # 清空现有商品
        for widget in self.products_grid.winfo_children():
            widget.destroy()
        
        if not products:
            no_products_frame = customtkinter.CTkFrame(self.products_grid, fg_color="transparent")
            no_products_frame.pack(expand=True, pady=50)
            
            no_products = customtkinter.CTkLabel(
                no_products_frame,
                text="🎯 No matching products found\n\nTry adjusting your search criteria or clear filters to view all products",
                font=("Arial", 13),
                text_color=Theme.get_color('fg_secondary'),
                justify="center"
            )
            no_products.pack(expand=True, padx=50)
            return
        
        # 创建网格布局
        self.create_products_grid(products)
    
    def create_products_grid(self, products):
        """创建商品网格布局 - 优化版（支持分批加载）"""
        # 网格容器
        if hasattr(self, 'grid_container'):
            self.grid_container.destroy()
        
        grid_container = customtkinter.CTkFrame(self.products_grid, fg_color="transparent")
        grid_container.pack(fill="both", expand=True)
        self.grid_container = grid_container
        
        # 根据设置计算每行商品数量
        # 根据每页商品数量动态调整列数
        if self.products_per_page <= 6:
            columns = 2
        elif self.products_per_page <= 9:
            columns = 3
        else:
            columns = 4
        
        self.grid_columns = columns
        self.all_products = products
        self.displayed_count = 0
        
        # 初始加载更多商品（而不是一次性加载所有）
        self.load_products_batch(size=20)  # 先加载20个
        
        # 配置网格权重
        for i in range(columns):
            grid_container.columnconfigure(i, weight=1)
    
    def load_products_batch(self, size=20):
        """分批加载商品 - 提升性能"""
        if not hasattr(self, 'all_products') or self.displayed_count >= len(self.all_products):
            return
        
        # 计算要加载的商品范围
        end_idx = min(self.displayed_count + size, len(self.all_products))
        products_to_load = self.all_products[self.displayed_count:end_idx]
        
        row = self.displayed_count // self.grid_columns
        col = self.displayed_count % self.grid_columns
        
        for product in products_to_load:
            # 创建商品卡片
            product_card = self.create_product_card(product, self.grid_container)
            
            # 网格布局
            product_card.grid(
                row=row, 
                column=col, 
                padx=12, 
                pady=12, 
                sticky="nsew"
            )
            
            # 更新位置
            col += 1
            if col >= self.grid_columns:
                col = 0
                row += 1
        
        self.displayed_count = end_idx
        
        # 如果还有更多商品，延迟加载下一批
        if self.displayed_count < len(self.all_products):
            self.after(100, lambda: self.load_products_batch(size))
        else:
            # 配置最终的行权重
            final_row = (len(self.all_products) + self.grid_columns - 1) // self.grid_columns
            for i in range(final_row + 1):
                self.grid_container.rowconfigure(i, weight=1)
    
    def create_product_card(self, product, parent=None):
        """创建单个商品卡片；parent 可选，默认为 self.products_grid"""
        if parent is None:
            parent = self.products_grid
        
        # 获取当前卡片尺寸设置
        card_config = self.card_sizes.get(self.card_size, self.card_sizes['medium'])
        
        # 使用 CustomTkinter 框架创建卡片
        card = customtkinter.CTkFrame(
            parent,
            fg_color=("gray95", "gray20"),
            corner_radius=15,
            border_width=1,
            border_color=Theme.get_color('border')
        )
        
        # 商品图片区域
        image_frame = customtkinter.CTkFrame(card, fg_color="transparent")
        image_frame.pack(pady=15, padx=15)
        
        # 图片显示容器 - 设置固定尺寸以适配网格宽度
        image_container = tk.Frame(
            image_frame, 
            width=card_config['image_width'], 
            height=card_config['image_height'],
            bg=Theme.get_color('bg_primary')
        )
        image_container.pack()
        image_container.pack_propagate(False)  # 保持固定尺寸
        
        # 图片占位符 - 无边框，填充整个容器
        image_placeholder = tk.Label(
            image_container,
            text="🖼️\nProduct Image",
            font=("Arial", 14),
            fg="#999999",
            bg=Theme.get_color('bg_primary'),
            justify="center",
            anchor="center"
        )
        
        # 异步加载商品图片
        img_path = getattr(product, 'image_path', None)
        if img_path:
            def on_image_loaded(img, error):
                if img and not error:
                    # img 已经是 PhotoImage 对象，直接使用
                    image_placeholder.config(image=img, text='', bg=Theme.get_color('bg_primary'))
                    image_placeholder.image = img  # 保持引用
                elif error:
                    warning(f"Loading product image failed: {product.name} - {str(error)}")
                    image_placeholder.config(text="❌ Load Failed", bg="#FFE0E0")
            
            # 使用卡片的推荐尺寸加载图片
            load_image_async(card, img_path, (card_config['image_width'], card_config['image_height']), on_image_loaded)
        else:
            image_placeholder.config(bg="#F0F0F0")
        
        image_placeholder.pack(fill="both", expand=True)
        
        # 信息容器
        info_container = customtkinter.CTkFrame(card, fg_color="transparent")
        info_container.pack(pady=(0, 10), padx=15, fill="x")
        
        # 商品名称 - 使用英文名称
        name_label = customtkinter.CTkLabel(
            info_container,
            text=product.get_display_name() if hasattr(product, 'get_display_name') else (getattr(product, 'name_en', None) or product.name),
            font=("Arial", 13, "bold"),
            text_color=Theme.get_color('fg_primary'),
            wraplength=card_config['image_width'] - 30,
            justify="center"
        )
        name_label.pack(pady=(0, 8))
        
        # 商品价格
        price_label = customtkinter.CTkLabel(
            info_container,
            text=f"¥{product.price:.2f}",
            font=("Arial", 16, "bold"),
            text_color=Theme.get_color('accent')
        )
        price_label.pack(pady=4)
        
        # 库存状态
        stock_frame = customtkinter.CTkFrame(info_container, fg_color="transparent")
        stock_frame.pack(pady=5)
        
        if product.stock > 10:
            stock_text = f"✅ In Stock ({product.stock})"
            stock_color = Theme.get_color('success')
        elif product.stock > 0:
            stock_text = f"⚠️ Low Stock ({product.stock})"
            stock_color = Theme.get_color('warning')
        else:
            stock_text = "❌ Out of Stock"
            stock_color = Theme.get_color('error')
        
        stock_badge = customtkinter.CTkLabel(
            stock_frame,
            text=stock_text,
            font=("Arial", 10),
            text_color=stock_color
        )
        stock_badge.pack()
        
        # 操作按钮容器
        button_container = customtkinter.CTkFrame(card, fg_color="transparent")
        button_container.pack(pady=(5, 15), padx=15)
        
        # 加入购物车按钮
        accent_color = Theme.get_color('accent')
        add_to_cart_btn = customtkinter.CTkButton(
            button_container,
            text="🛒 Add to Cart",
            command=lambda p=product: self.add_to_cart(p),
            width=180,
            height=35,
            font=("Arial", 12, "bold"),
            fg_color=accent_color,
            hover_color=Theme.get_color('accent_hover'),
            corner_radius=8
        )
        add_to_cart_btn.pack()
        
        # 为整个卡片绑定点击事件（点击任意区域进入详情页）
        def on_card_click(event, p=product):
            # 如果点击的是按钮，不触发详情页跳转
            if event.widget == add_to_cart_btn or event.widget in add_to_cart_btn.winfo_children():
                return
            self.view_product_detail(p)
        
        # 添加鼠标悬停效果
        def on_enter(e):
            card.configure(border_color=accent_color)
        
        def on_leave(e):
            card.configure(border_color=Theme.get_color('border'))
        
        card.bind("<Enter>", on_enter)
        card.bind("<Leave>", on_leave)
        card.configure(cursor="hand2")
        
        # 为卡片内所有子组件也绑定相同事件（除了按钮）
        def bind_click_to_widgets(widget, exclude_widgets=None):
            if exclude_widgets is None:
                exclude_widgets = [add_to_cart_btn]
            
            if widget not in exclude_widgets and isinstance(widget, (tk.Frame, customtkinter.CTkFrame)):
                widget.bind("<Button-1>", on_card_click)
                # 递归绑定子组件
                for child in widget.winfo_children():
                    bind_click_to_widgets(child, exclude_widgets)
        
        bind_click_to_widgets(card)
        
        return card
    
    def reset_filter_fields(self):
        """重置筛选字段"""
        self.category_var.set("all")
        self.price_var.set("all")
        self.min_price_var.set("")
        self.max_price_var.set("")
        self.stock_var.set("all")
        self.sort_var.set("name_asc")
    
    def clear_filters(self):
        """清除所有筛选"""
        self.reset_filter_fields()
        self.filter_status_label.configure(text="Showing all products", text_color=Theme.get_color('fg_secondary'))
        self.clear_filter_btn.configure(state="disabled")
        self.current_filters = {}
        self.load_products()
    
    def load_products(self, search_term=None):
        """加载商品列表"""
        debug("Loading products...")
        
        # 清空现有商品
        for widget in self.products_grid.winfo_children():
            widget.destroy()
        
        # 显示加载指示器
        loading_overlay = show_loading(self.products_grid, "Loading products...")
        
        def load_products_operation():
            """加载商品的操作函数"""
            # 获取商品数据
            products = self.controller.product_service.get_all_products()
            
            # 应用搜索过滤
            if search_term and search_term != "Search products...":
                products = [p for p in products if search_term.lower() in p.name.lower()]
            
            return products
        
        def on_products_loaded(products, error):
            """商品加载完成回调"""
            # 隐藏加载指示器
            hide_loading(loading_overlay)
            
            if error:
                error(f"Failed to load products: {str(error)}")
                messagebox.showerror(t("common.error"), t("product.load_failed", error=str(error)))
                return
            
            # 更新商品计数
            self.product_count_label.configure(text=f"Found {len(products)} products")
            
            if not products:
                no_products_frame = customtkinter.CTkFrame(self.products_grid, fg_color="transparent")
                no_products_frame.pack(expand=True, pady=50)
                
                no_products = customtkinter.CTkLabel(
                    no_products_frame,
                    text="🔍 No products found\n\nTry using different search terms or clear the search",
                    font=("Arial", 13),
                    text_color=Theme.get_color('fg_secondary'),
                    justify="center"
                )
                no_products.pack(expand=True, padx=50)
                return
            
            # 创建商品网格
            self.create_products_grid(products)
        
        # 异步加载商品
        import threading
        def load_worker():
            try:
                products = load_products_operation()
                self.after(0, lambda: on_products_loaded(products, None))
            except Exception as e:
                self.after(0, lambda: on_products_loaded(None, e))
        
        thread = threading.Thread(target=load_worker, daemon=True)
        thread.start()
    
    def search_products(self):
        """搜索商品"""
        search_term = self.search_entry.get().strip()
        
        # 保存搜索历史
        if search_term and search_term != "Search products...":
            self.save_search_term(search_term)
        
        self.load_products(search_term)
    
    def quick_search(self, keyword):
        """快速搜索（点击热门或历史关键词）"""
        self.search_entry.delete(0, tk.END)
        self.search_entry.insert(0, keyword)
        self.search_products()
    
    def load_search_history(self):
        """加载搜索历史"""
        try:
            from core.services.data_manager import DataManager
            dm = DataManager()
            history_data = dm.load_data('search_history.json') or {}
            
            # 获取当前用户ID
            user_id = None
            if self.controller.auth_service.is_logged_in():
                user_id = self.controller.auth_service.current_user.user_id
            
            if user_id and user_id in history_data.get('user_histories', {}):
                self.search_history = history_data['user_histories'][user_id]
            else:
                self.search_history = history_data.get('global_history', [])
                
        except Exception as e:
            error(f"加载搜索历史失败: {e}")
            self.search_history = []
    
    def save_search_term(self, search_term):
        """保存搜索词到历史"""
        try:
            from core.services.data_manager import DataManager
            dm = DataManager()
            history_data = dm.load_data('search_history.json') or {'global_history': [], 'user_histories': {}}
            
            # 获取当前用户ID
            user_id = None
            if self.controller.auth_service.is_logged_in():
                user_id = self.controller.auth_service.current_user.user_id
            
            # 选择存储位置
            if user_id:
                if user_id not in history_data['user_histories']:
                    history_data['user_histories'][user_id] = []
                target_history = history_data['user_histories'][user_id]
            else:
                target_history = history_data['global_history']
            
            # 移除重复项
            if search_term in target_history:
                target_history.remove(search_term)
            
            # 添加到开头
            target_history.insert(0, search_term)
            
            # 限制历史记录数量
            if len(target_history) > 10:
                target_history = target_history[:10]
            
            # 保存到文件
            dm.save_data('search_history.json', history_data)
            
            # 更新本地历史
            self.search_history = target_history
            self.update_search_history_display()
            
        except Exception as e:
            error(f"保存搜索历史失败: {e}")
    
    def update_search_history_display(self):
        """更新历史搜索显示"""
        # 检查history_container是否存在
        if not hasattr(self, 'history_container') or not self.history_container:
            return
        
        # 清空现有历史按钮
        for widget in self.history_container.winfo_children():
            widget.destroy()
        
        # 显示最近5条历史记录
        recent_history = self.search_history[:5]
        for keyword in recent_history:
            history_frame = customtkinter.CTkFrame(self.history_container, fg_color="transparent")
            history_frame.pack(side="left", padx=3)
            
            # 历史搜索按钮
            history_btn = customtkinter.CTkButton(
                history_frame,
                text=keyword,
                command=lambda k=keyword: self.quick_search(k),
                width=100,
                height=28,
                font=('Arial', 10),
                fg_color=("gray85", "gray28"),
                hover_color=Theme.get_color('accent_hover')
            )
            history_btn.pack(side="left")
            
            # 删除按钮
            delete_btn = customtkinter.CTkButton(
                history_frame,
                text="×",
                command=lambda k=keyword: self.remove_search_history(k),
                width=28,
                height=28,
                font=('Arial', 14),
                fg_color='#E74C3C',
                hover_color='#C0392B'
            )
            delete_btn.pack(side="left", padx=(3, 0))
        
        # 清空历史按钮（如果有历史记录）
        if recent_history:
            clear_history_btn = customtkinter.CTkButton(
                self.history_container,
                text=t("product.search.clear_history"),
                command=self.clear_search_history,
                width=100,
                height=28,
                font=('Arial', 10),
                fg_color='gray',
                hover_color='darkgray'
            )
            clear_history_btn.pack(side="left", padx=(15, 0))
    
    def remove_search_history(self, keyword):
        """删除单个搜索历史"""
        try:
            if keyword in self.search_history:
                self.search_history.remove(keyword)
                self.save_search_history_to_file()
                self.update_search_history_display()
        except Exception as e:
            error(f"删除搜索历史失败: {e}")
    
    def clear_search_history(self):
        """清空所有搜索历史"""
        try:
            self.search_history = []
            self.save_search_history_to_file()
            self.update_search_history_display()
        except Exception as e:
            error(f"清空搜索历史失败: {e}")
    
    def save_search_history_to_file(self):
        """保存搜索历史到文件"""
        try:
            from core.services.data_manager import DataManager
            dm = DataManager()
            history_data = dm.load_data('search_history.json') or {'global_history': [], 'user_histories': {}}
            
            # 获取当前用户ID
            user_id = None
            if self.controller.auth_service.is_logged_in():
                user_id = self.controller.auth_service.current_user.user_id
            
            # 更新对应位置的历史
            if user_id:
                if user_id not in history_data['user_histories']:
                    history_data['user_histories'][user_id] = []
                history_data['user_histories'][user_id] = self.search_history
            else:
                history_data['global_history'] = self.search_history
            
            dm.save_data('search_history.json', history_data)
        except Exception as e:
            error(f"保存搜索历史到文件失败: {e}")
    
    def _debounced_search(self):
        """防抖搜索 - 延迟执行搜索"""
        if hasattr(self, '_search_timer'):
            self.after_cancel(self._search_timer)
        
        def delayed_search():
            self.search_products()
        
        self._search_timer = self.after(300, delayed_search)  # 300ms延迟，更快的响应
    
    def view_product_detail(self, product):
        """查看商品详情"""
        # 跳转到商品详情页面
        self.controller.show_page('ProductDetailPage', product_id=product.product_id)
    
    def add_to_cart(self, product):
        """添加商品到购物车"""
        info(f"Adding {product.name} to cart")
        
        if not self.controller.auth_service.is_logged_in():
            result = messagebox.askyesno(
                "🔐 Login Required", 
                "You need to log in to add items to your cart.\n\nWould you like to log in now?"
            )
            if result:
                self.controller.show_page("LoginPage")
            return
        
        # 检查库存
        if not self.controller.product_service.check_stock_availability(product.product_id, 1):
            messagebox.showerror(
                t("product.cart_actions.stock_insufficient"), 
                t("product.cart_actions.stock_insufficient_message", name=product.name)
            )
            return
        
        try:
            # 用户已登录，添加到购物车
            self.controller.shopping_cart.add_item(product)
            
            # 更新购物车数量显示
            self.update_cart_display()
            
            messagebox.showinfo(t("common.success"), t("product.added_to_cart", product_name=product.name))
        except ValueError as e:
            messagebox.showerror(t("common.error"), str(e))
    
    def update_cart_display(self):
        """更新购物车显示"""
        cart_count = self.controller.shopping_cart.total_items
        if cart_count > 0:
            # 显示购物车数量
            self.cart_count_label.place(in_=self.cart_btn, relx=1.0, x=0, y=0, anchor="ne")
            self.cart_count_label.config(text=str(cart_count))
        else:
            self.cart_count_label.place_forget()
    
    def show_cart(self):
        """Show the Cart page. Require login first; CartPage will render the cart contents."""
        if not self.controller.auth_service.is_logged_in():
            messagebox.showwarning(t("product.navigation.login_required"), t("product.navigation.login_required_cart"))
            self.controller.show_page("LoginPage")
            return

        # Navigate to the dedicated Cart page (it will handle empty-cart messaging)
        try:
            self.controller.show_page("CartPage")
        except Exception:
            # Fallback: show a simple message if CartPage is not available
            cart = self.controller.shopping_cart
            if not cart.items:
                messagebox.showinfo(t("cart.title"), t("cart.empty_message"))
            else:
                messagebox.showinfo(t("cart.title"), t("cart.items_count", count=cart.total_items))
    
    def show_orders(self):
        """显示订单"""
        if not self.controller.auth_service.is_logged_in():
            messagebox.showwarning(t("product.navigation.login_required"), t("product.navigation.login_required_orders"))
            self.controller.show_page("LoginPage")
            return
        # Navigate to the OrdersPage (will call update_data)
        try:
            self.controller.show_page("OrdersPage")
        except Exception:
            # Fallback: notify the user
            messagebox.showinfo(t("orders.title"), t("orders.coming_soon"))
    
    def show_profile(self):
        """显示个人中心"""
        if self.controller.auth_service.is_logged_in():
            # 如果已登录，跳转到独立的 AccountPage
            self.controller.show_page("AccountPage")
        else:
            result = messagebox.askyesno("🔐 Account", "You are not currently logged in.\n\nWould you like to log in or create an account?")
            if result:
                self.controller.show_page("LoginPage")
    
    def update_data(self):
        """更新页面数据"""
        # 更新购物车显示
        self.update_cart_display()
        
        # 重新加载搜索历史（用户可能已切换）
        self.load_search_history()
        self.update_search_history_display()
    
    def on_show(self):
        """页面显示时调用"""
        if hasattr(self, 'role_switcher'):
            self.role_switcher.update_display()
        
        # 如果有当前筛选，重新应用
        if self.current_filters:
            self.apply_filter_logic(self.current_filters)